package common

import (
	"context"
	"encoding/json"
	"github.com/gorhill/cronexpr"
	"log"
	"net"
	"net/http"
	"time"
)

func GetIp() (ip string, err error) {

	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return
	}
	for _, addr := range addrs {
		ipNet, isNet := addr.(*net.IPNet)
		if isNet && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				ip = ipNet.IP.String()
				return
			}
		}
	}

	return
}

func BuildResponse(w http.ResponseWriter, errno int, msg string, data interface{}) {
	response := Response{
		Errno: errno,
		Msg:   msg,
		Data:  data,
	}
	res, err := json.Marshal(response)
	if err != nil {
		log.Println(err)
		w.Write([]byte(`{"Errno":20000}`))
	} else {
		w.Write(res)

	}
	return
}

func UnPackJob(jobByte []byte) (job *Job, err error) {
	job = &Job{}
	if err = json.Unmarshal(jobByte, job); err != nil {
		return
	}
	return
}

func BuildJobPlan(job *Job) (err error) {
	var (
		expr *cronexpr.Expression
	)
	if expr, err = cronexpr.Parse(job.CronExpr); err != nil {
		return
	}
	job.Expr = expr
	job.NextTime = expr.Next(time.Now())
	job.Ctx, job.Cancel = context.WithCancel(context.TODO())
	return
}
